package com.itheima.smspringboot.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.smspringboot.common.Result;
import com.itheima.smspringboot.entity.Admin;
import com.itheima.smspringboot.exception.CustomerExpception;
import com.itheima.smspringboot.mapper.AdminMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminService {
    @Resource
    private final AdminMapper adminMapper;

    public AdminService(AdminMapper adminMapper) {
        this.adminMapper = adminMapper;
    }

    public String adminLogin(String username) {
        if("admin".equals(username)) {
            return "admin";
        }else {
            throw new CustomerExpception("用户名错误");
        }

    }



    public List<Admin> selectAllAdmin(Admin admin) {
        return adminMapper.selectAll(admin);
    }

    public PageInfo selectPage(Integer pageNum, Integer pageSize,Admin admin) {
        //H=开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);


    }

    public void add(Admin admin) {

        Admin dbadmin = adminMapper.selectByUsername(admin.getUsername());
        if (dbadmin != null) {
            throw new CustomerExpception("账号重复");
        }

        //如果密码为空，默认密码为admin
        if (StrUtil.isBlankIfStr(admin.getPassword())) {
            admin.setPassword("admin");
        }

        adminMapper.insert(admin);
    }

    public void updateById(Admin admin) {
        adminMapper.updateById(admin);
    }

    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }


    public void deleteBatch(List<Admin> adminList) {
        for (Admin admin : adminList) {
            this.deleteById(admin.getId());
        }
    }

    public Admin login(Admin admin) {
        return adminMapper.selectByUsername(admin.getUsername());

    }

    public void register(Admin admin) {

        Admin dbadmin = adminMapper.selectByUsername(admin.getUsername());

        if ( dbadmin!= null){
            throw new CustomerExpception("该用户名已存在，请更换用户名");
        }else {
            if (StrUtil.isBlankIfStr(admin.getName())) {
                admin.setName("admin");
            }
            adminMapper.insert(admin);
        }

    }
}
